/*
全局工具类
时间处理，统一用dayjs即可
*/
import { ExclamationCircleOutlined } from "@ant-design/icons-vue"
import { Modal } from "ant-design-vue"
import { createVNode } from "vue"
import { useMainStore } from '@/store'
import _ from 'lodash-es'
// import { useDictStore } from '@/store/dict'

// const dictStore = useDictStore()


/**
 * 通过key的list 返回数据字典中中的集合 或者name
 * 
 * @param {*} 
 * sourceKeyList 数据字典的key的list ,根据key的list集合 一层一层的往下找 最后找到指定字典的children
 * sourceCode 数据字典的code 如果需要返回name 则传第二参数
 * 
 * @returns 
 */
export const mapDict = (sourceKeyList=[],sourceCode='') => {
    const mainStore = useMainStore()
    let $sourceList = [];
    let $dictTreeAll = mainStore.dictTreeAll;
    // console.log(mainStore,mainStore.dictTreeAll,'$dictTree');
    
    // 根据key的list 一层一层的往下找
    function getDictTree(keyList,source){
        if(keyList.length>0){
            let $key =keyList[0]
            let $res = source.find(item=>item.code === $key)?.children;
            if(keyList.length>1){
                return getDictTree(keyList.slice(1),$res)
            }else{
                return $res
            }
        }
    }
    $sourceList = getDictTree(sourceKeyList,$dictTreeAll)
    if(sourceCode){
        return $sourceList.find(item=>item.code === sourceCode)?.name || '--'
    }else{
        return $sourceList
    }

}


/**
 * 删除确认框
 * @param {*} onOkCB {fn}
 * @param {*} onCancelCB  {fn}
 * @param {*} modalConfig {content:xxx}  modal弹框配置项
 * @returns
 */
export const deleteConfirmModal=async (onOkCB=null,onCancelCB=null,modalConfig={})=>{
    const {content,title,icon,okText,cancelText} = modalConfig

    Modal.confirm({
        title: title ? title : '提示',
        icon: icon ? icon : createVNode(ExclamationCircleOutlined),
        content: content ? content : '确定删除该条数据吗？',
        okText: okText ? okText : '确定',
        cancelText: cancelText ? cancelText : '取消',
        async onOk(){
            onOkCB && await onOkCB.fn()
        },
        async onCancel(){
            onCancelCB && await onCancelCB.fn()
        }
    })
}
export const toggleFullScreen = (containerClassName, cb) => {
    const containerDom = document.querySelector('.' + containerClassName);
    if (containerDom) {
        containerDom.requestFullscreen()
        /*if (containerDom.className.includes('full')) {
			containerDom.className = containerDom.className.replace('full', '');
			cb && cb(false)
		} else {
			containerDom.className = containerDom.className + ' full';
			cb && cb(true)
		}*/
    }
}

// 根据eqCode  获取播放视屏的播放
export const getVideoPlayUrl = (data) => {
    const mainStore = useMainStore()
    let videoServe = mainStore.dictTree.find(r=>r.code==='videoServe')?.children || [];
    let videoUrl = videoServe.find(r=>r.code==='videoServerUrl')?.value || '';
    // console.log(videoServe,'videoServe',videoUrl);
    if(videoUrl && data){
        return  `${videoUrl}${data}.live.flv`;
    }else{
        return ''
    }
}

// 多个设备名称时  格式化设备名称
export const eqNameFormater = (name,posi) => {
    let nameList = name.split(',')
    if(nameList.length>1){
        let $text= `${nameList[0]} 等 <span style="color:#329AFE"> ${nameList.length} </span> 个${posi?'位置':'设备'}`;
        return $text;
    }else{
        return name
    }
}
export const vali24Hour =({list,text1,startField,endField})=>{
    let errorText = '';
    let valiList = _.cloneDeep(list);
    valiList.map(item=>{
        if(!item[startField] || !item[endField]){
            errorText = '时间段不能为空'
        }
    })
    valiList.sort((a,b)=>{
        let aT = new Date(`2022-01-01 `+a[startField]).valueOf()
        let bT = new Date(`2022-01-01 `+b[startField]).valueOf()
        return aT-bT
    })
    valiList.forEach((item, index) => {
        if (item[startField] > item[endField]) {
            errorText ='开始时间需要早于结束时间'
        }
        if(valiList[index + 1]){
            if(valiList[index][endField] > valiList[index + 1][startField]){
                errorText = text1 +'时段有冲突'
            }
        }
    })
    return errorText
}

// blob导出文件
export const downloadExcelByBlob =(res, fileName) =>{
    // let blob= new Blob([res], { type: 'application/vnd.ms-excel' });
    let blob= new Blob([res], { type: 'application/octet-stream' });

    // let blob= new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    let url = window.URL.createObjectURL(blob)
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.href = url;
    a.download = fileName;
    a.target = "_blank";
    a.click();
    a.remove();
}

// blob导出zip文件
export const downloadZipByBlob = (res, fileName) => {
    let blob= new Blob([res], { type: 'application/zip'});
    let url = window.URL.createObjectURL(blob);
    // window.open(url,'_blank');
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.href = url;
    a.download = fileName;
    a.target = "_blank";
    a.click();
    a.remove();
} 
// base64转excel导出
export const downloadFileByBase64 = (data, fileName)=>  {
    // 使用atob方法解码base64
    let raw = window.atob(data);
    // 创建一个存储解码后数据的数组
    let uInt8Array = new Uint8Array(raw.length);
    // blob只能接收二进制编码，需要讲base64转为二进制再塞进去
    for (let i = 0; i < raw.length; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    // 这里给了一个返回值，在别的方法掉用传入base64编码就可以得到转化后的blob
    const link = document.createElement('a')
    const blob = new Blob([uInt8Array], { type: 'application/vnd.ms-excel' })
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    //设置下载的Excel表名
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}
// 数字千分位加逗号处理
export const toThousands = (num)=> {
    if (!num || num === 0) return 0
    num = num + ''
    let showNum = num.split('.')
    return showNum[0].replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + (showNum[1] ? `.${showNum[1]}` : '')
}
/*
异常日志抛出
errName： 自定义名称
errorObj : 捕获的错误对象
fileInfo: 错误位置信息
*/
export function GetQueryObj() {
    let url = window.location.href; //获取url中"?"符后的字串
    let paramsObj = new Object();
    if (url.indexOf("?") !== -1) {
        let str = url.split('?')[1].split("&");
        for (let i = 0; i < str.length; i++) {
            paramsObj[str[i].split("=")[0]] = decodeURI(str[i].split("=")[1]);
        }
    }
    return paramsObj;
}
export function getPermission(route, permission) {
    let menuList = JSON.parse(localStorage.getItem('permissions'))
    if(!(menuList&&menuList.length>0)){
        return true
    }
    let flag = false
    function getPermission(arr) {
        arr.forEach(item=>{
            if(item.permission === permission) {
                flag = true
            }
            if(item.children.length>0) {
                getPermission(item.children)
            }
        })
    }
    getPermission(menuList)
    return true
}
